// 菜单管理
<template>
    <div class="menu_main">
        <modalForm ref="modalForm" :pidArr="state.pidArr" @success="init" :menuTypeList="state.menuTypeList">
        </modalForm>
        <!-- <div class="tab_box">
            <div class="tab_item" v-for="(item, index) in state.platformTypeList" :key="index"
                 :class="state.platform_type === item.dict_code ? 'tab_item_active' : ''" @click="tabChange(item.dict_code)">{{ item.dict_name }}</div>
        </div> -->
        <div class="safelist-search-container mb-16">
            <a-row class="search-row">
                <a-col :span="6" class="mr-8">
                    <a-input v-model:value="state.searchData.name" placeholder="请输入菜单名称1" />
                </a-col>
                <!-- <a-col :span="5" class="mr-16">
                    <a-select v-model:value="state.searchData.menu_status" placeholder="请选择状态"
                              style="width: 100%;" optionFilterProp="label">
                        <a-select-option value="">全部</a-select-option>
                        <a-select-option value="1">显示</a-select-option>
                        <a-select-option value="0">隐藏</a-select-option>
                    </a-select>
                </a-col> -->
                <a-col :span="6">
                    <a-button type="primary" class="mr-8" @click="handleSearch">搜索</a-button>
                    <a-button type="primary" ghost @click="handleEmpty">重置</a-button>
                </a-col>
            </a-row>
            <a-row>
                <a-button type="primary" class="mr-8" ghost @click="expandRows(true)">展开全部</a-button>
                <a-button type="primary" class="mr-8" ghost @click="expandRows(false)">折叠全部</a-button>
                <a-button type="primary" class="nmc-add-btn-primary" @click="addMenu">新增</a-button>
            </a-row>
        </div>
        <div class="safelist-table-container">
            <a-table :columns="tableProps.columns" :data-source="tableProps.dataSource" :pagination="false"
                :defaultExpandAllRows="state.defaultExpandAllRows" :expandedRowKeys="state.expandedRowKeys"
                @expandedRowsChange="expandedRowsChange" :scroll="{ y: 'calc(100vh - 200px)' }"
                childrenColumnName='childrenList' rowKey="id">
                <template #bodyCell="{ column, text, record }">
                    <div v-if="column.key === 'action'" class="action_box">
                        <span @click="editMenu(record)">编辑</span>
                        <span @click="addMenu(record)">新增</span>
                        <span class="delete_btn" @click="deleteMenu(record)">删除</span>

                        <span @click="addQueryBtn(record)">增加查看</span>
                    </div>
                    <!-- <div v-if="column.dataIndex === 'menu_url'" class="router_box">
                        {{ text }}
                    </div> -->
                    <div v-if="column.dataIndex === 'type'">
                        <!--                        {{text==='1'?'目录':text==='2'?'菜单':'按钮'}}-->
                        {{state.menuTypeList?.find(r => r.value === text)?.label}}
                    </div>
                    <div v-if="column.dataIndex === 'isActive'" :class="text ? 'show' : 'none'">
                        {{ text ? '显示' : '隐藏' }}
                    </div>
                </template>
            </a-table>
        </div>
    </div>
</template>

<script>
import { computed, createVNode, onMounted, reactive, ref, watch } from 'vue'
import { sysResourceDelete, sysResourceQueryAll } from '@/service/api'
import { treeDataFormat, } from "@/utils";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
import { message, Modal } from 'ant-design-vue';
import modalForm from './modalForm.vue'
import { sysResourceAdd, sysResourceUpdate } from "@/service/api";
// import { useStore } from "vuex";
// import { useMainStore } from '@/store/main'
export default {
    components: { modalForm },
    setup() {
        // const mainStore = useMainStore()
        const modalForm = ref()
        const tableProps = ref({
            columns: [
                {
                    title: '菜单名称',
                    dataIndex: 'name',
                    width: 200
                },
                {
                    title: '排序',
                    dataIndex: 'displayIndex',
                    width: 70
                },
                {
                    title: '请求地址',
                    dataIndex: 'content',
                    ellipsis: true,
                    // width: 200
                },
                {
                    title: '类型',
                    dataIndex: 'type',
                    width: 80
                    // render: (text) => mapDictTypeToName(dictType, 'menuType', text, 'code')
                },
                {
                    title: '可见',
                    dataIndex: 'isActive',
                    // render: (text) => text === '1' ? '显示' : '隐藏'
                },
                {
                    title: '权限标识',
                    dataIndex: 'permission',
                    width: 150
                },
                {
                    title: '创建时间',
                    dataIndex: 'createTime',
                    width: '160px'
                },
                {
                    title: '操作',
                    key: 'action',
                    width: '210px'
                }
            ],
            dataSource: [], //列表数据
            // pagination: {
            //     current: 1,//当前页数
            //     pageSize: 20,//每页条数
            //     total: 0,
            //     showSizeChanger: true,
            //     showTotal: (total) => `共有${total}条数据`,
            //     onChange: (current, pageSize) => {
            //         tableProps.value.pagination.current = current;
            //         tableProps.value.pagination.pageSize = pageSize;
            //         init();
            //     }
            // }
        })
        const state = reactive({
            // platform_type: '1',   //类型  平台 手机 
            searchData: {
                name: '',

            },//搜索数据
            defaultExpandAllRows: true,//初始时，是否展开所有行
            expandedRowKeys: [], // 打开的行
            pidArr: [],  //原始数据的tree结构

            // platformTypeList: [],
            menuTypeList: [{ label: '目录', value: 'module' },
            { label: '菜单', value: 'menu' },
            { label: '按钮', value: 'button' }
            ]
        })
        let primitiveData = [] //原始数据
        onMounted(() => {

            init(1);

        })

        const addQueryBtn = (record) => {
            let $data = {
                ... {
                    "id": "", "parentId": record.id, "name": "查看", "type": "button",
                    "content": "", "permission": ":query",
                    "displayIndex": "1", "isActive": true, "isOutLink": false, "moduleId": "",
                    "icon": "", "groupId": "", "remark": ""
                },
                parentId: record.id
            }

            sysResourceAdd($data).then(res => {
                if (res.result) {

                    // formRef.value.resetFields()

                    init()
                }
            })
        }
        //获取列表数据
        const init = (type) => {
            sysResourceQueryAll({

            }).then(res => {
                if (res.result) {
                    primitiveData = res.result || [];
                    filterTableData();
                    if (type) {

                        expandRows(true)

                    }
                }
            })
        }

        const filterTableData = () => {
            // let $platform_type = state.platform_type;
            let tableData = JSON.parse(JSON.stringify(primitiveData));
            // if(primitiveData[$platform_type]){
            //     tableData = JSON.parse(JSON.stringify(primitiveData[$platform_type])) 
            //     // state.expandedRowKeys = []
            // }else{
            //     tableData = []
            // }
            // 原始数据的tree结构
            state.pidArr = tableData || [];

            // 增加搜索功能
            tableData = tableDataSearch(tableData)


            tableProps.value.dataSource = tableData;
            //展开所有行
            // getId(tableProps.value.dataSource)
        }
        //搜索数据
        const tableDataSearch = (tableData) => {
            let $name = state.searchData.name.trim();
            // let $menu_status = state.searchData.menu_status;
            if (!$name) return tableData;
            let tree = []
            tableData.forEach(item => {
                // item.name
                // 如果自身匹配
                if (item.name.indexOf($name) != -1) {
                    // if(item.childrenList){
                    //     let $childrenList = tableDataSearch(item.childrenList)
                    //     if($childrenList.length){
                    //         item.childrenList = $childrenList
                    //     }else{
                    //         delete item.childrenList
                    //     }
                    // }
                    tree.push(item);
                } else {
                    console.log(item.name, 'item.name--item.name');
                    if (item.childrenList) {
                        let cc = tableDataSearch(item.childrenList);
                        console.log(cc, 'cc---cc', item.childrenList);
                        tree = tree.concat(cc)
                    }
                }
            })
            return tree


        }

        //搜索
        const handleSearch = () => {
            // tableProps.value.pagination.current = 1;
            init()
        }
        //重置
        const handleEmpty = () => {
            state.searchData = {
                name: '',

            }
            filterTableData();

        }
        // 新增菜单
        const addMenu = (record) => {

            modalForm.value.showModal({
                title: '新增菜单',
                parentId: record.id,
                // platform_type: state.platform_type
            })
        }
        // 编辑菜单
        const editMenu = (record) => {
            console.log(record, '编辑菜单')
            modalForm.value.showModal({
                title: '编辑菜单',
                ...record,
                // platform_type: state.platform_type
            })
        }
        // 展开行变化
        const expandedRowsChange = (key) => {
            state.expandedRowKeys = key
        }

        // 确认删除菜单
        const deleteMenu = (record) => {
            Modal.confirm({
                title: '提示',
                icon: createVNode(ExclamationCircleOutlined),
                content: '您是否要删除当前菜单？',
                okText: '确认',
                cancelText: '取消',
                onOk() {
                    return new Promise((resolve, reject) => {
                        sysResourceDelete({
                            id: record.id,
                            "isActive": record.isActive,
                            "parentId": record.parentId
                        }).then(res => {
                            if (res.result) {
                                message.success('删除成功');
                                init()
                                resolve()
                            }
                        }).catch(err => {
                            resolve()
                            message.error(err.message);
                        })
                    })
                },
            });
        }
        // 展开收起所有行
        const expandRows = (flag) => {
            if (flag) {
                getId(tableProps.value.dataSource)
            } else {
                state.expandedRowKeys = []
            }
        }
        const getId = (arr) => {
            // console.log(arr,'arr----arr');
            arr.forEach(item => {
                state.expandedRowKeys.push(item.id)
                if (item.childrenList && item.childrenList.length > 0) {
                    getId(item.childrenList)
                }
            })
        }
        return {
            init,
            // tabChange,
            state,
            tableProps,
            handleSearch,
            handleEmpty,
            addMenu,
            expandedRowsChange,
            deleteMenu,
            editMenu,
            expandRows,
            modalForm,
            addQueryBtn
        }
    },
}
</script>
<style lang="less" scoped>
.menu_main {
    height: 100%;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .tab_box {
        display: flex;
        margin-bottom: 15px;
        // border-bottom: 1px solid rgba(22, 66, 131, 1);
        font-family: PingFangSC-Semibold, PingFang SC, serif;
        font-size: 14px;

        .tab_item {
            padding: 0 0 10px;
            cursor: pointer;
            margin-right: 40px;
        }

        .tab_item_active {
            font-weight: 600;
            // color: #00cccc;
            // border-bottom: 2px solid #00cccc;
        }
    }
}

.safelist-table-container {
    height: calc(100% - 48px);
    overflow: hidden;

    .action_box {
        display: flex;
        font-size: 14px;
        color: #00cccc;

        span {
            cursor: pointer;
            margin-right: 8px;
        }

        .delete_btn {
            color: rgba(255, 47, 0, 1);
        }
    }

    .router_box {
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
    }

    .show {
        width: 40px;
        height: 18px;
        background: #0E3E6C;
        border-radius: 4px;
        color: rgba(36, 195, 142, 1);
        line-height: 18px;
        text-align: center;
    }

    .none {
        width: 40px;
        height: 18px;
        background: rgba(255, 255, 255, 0.14);
        border-radius: 4px;
        line-height: 18px;
        text-align: center;
        color: rgba(255, 255, 255, 0.25);
    }
}
</style>
